import { watchThrottled } from '@vueuse/core'
import { config } from "@/utils/setting"

const changeOperationWidth = (childNum, fontSize) => {
    return childNum && fontSize ? ((fontSize * 2 + 5) * childNum + 20) + "px" : "0"
}

export default (defaultNum = 4) => {
    const eleNum = defaultNum + 1
    let delay = 300
    const childrenNum = ref(eleNum)
    let timeout = null
    let animation = false
    let time = 0

    onBeforeUpdate(() => {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            childrenNum.value = 1
            const doms = document.querySelectorAll(".operation-column .cell")
            if (doms.length > 1) {
                const elements = document.querySelectorAll("colgroup col")
                if (!animation) {
                    for (let ele of elements) {
                        ele.style.transition = `all .5s`
                    }
                    setTimeout(() => {
                        for (let ele of elements) {
                            ele.style.transition = "none"
                        }
                    }, 1000)
                    animation = true
                    time = 500
                }
                for (let ele of doms) {
                    if (ele.childElementCount > childrenNum.value) childrenNum.value = ele.childElementCount
                }
            }
        }, time)
    })

    const width = ref("0")

    watchThrottled([childrenNum, () => config.value.fontSize], ([num, fontSize]) => {
        width.value = changeOperationWidth(num, fontSize)
    }, { throttle: delay, immediate: true })

    return width
}